/**
 * Created by Administrator on 2017/7/11.
 */
$(function(){

    /**
     * 左侧菜单开启状态管理
     *
     *
     * */
    if(window.localStorage.getItem('isSpread') === 'true') {
        $('.menu-spread').addClass('collapsed');
    }

   /* window.localStorage.setItem('isSpread',isSpread);*/

    $(document).on('click', '.spread-click', function (e) {
        if(window.localStorage.getItem('isSpread')==='true'){
            window.localStorage.setItem('isSpread',false);
            $('.menu-spread').removeClass('collapsed');
        }else{
            window.localStorage.setItem('isSpread',true);
            $('#main-menu .has-sub').map(function(index,ele) {
                $(ele).find('ul').removeAttr("style");
            });
            $('.menu-spread').addClass('collapsed');

        }
    });

    /**
     * ajax-form
     * 通过ajax提交表单，通过oneplus提示消息
     * 示例：<form class="ajax-form" method="post" action="xxx">
     */

    $(document).on('submit', 'form.ajax-form', function (e) {
        //取消默认动作，防止表单两次提交
        e.preventDefault();
        //禁用提交按钮，防止重复提交
        var form = $(this);
        $('[type=submit]', form).addClass('disabled');

        //获取提交地址，方式
        var action = $(this).attr('action');
        var method = $(this).attr('method');

        //检测提交地址
        if (!action) {
            return false;
        }

        //默认提交方式为get
        if (!method) {
            method = 'get';
        }

        //获取表单内容
        var formContent = $(this).serialize();

        //发送提交请求
        var callable;
        if (method == 'post') {
            callable = $.post;
        } else {
            callable = $.get;
        }
        callable(action, formContent, function (a) {
            handleAjax(a);
          /*  $('[type=submit]', form).removeClass('disabled');*/
        });

        //返回
        return false;
    });

    /**
     * ajax-form-access
     * 通过ajax提交表单，通过oneplus提示消息
     * 示例：<form class="ajax-form-access" method="post" action="xxx">
     */
    $(document).on('submit', 'form.ajax-form-access', function (e) {
        //取消默认动作，防止表单两次提交
        e.preventDefault();
        //禁用提交按钮，防止重复提交
        var form = $(this);
        $('[type=submit]', form).addClass('disabled');

        //获取提交地址，方式
        var action = $(this).attr('action');
        var method = $(this).attr('method');

        //检测提交地址
        if (!action) {
            toastr.error('提交地址为空!');
            return false;
        }

        //默认提交方式为get
        if (!method) {
            method = 'get';
        }

        //获取表单内容中选中chackbox值
        var objs =$('form  .cbr-checked ');
        var  checks= objs.map(function(index,domElement){
            return $(domElement).find("div input[type='checkbox']").attr('value');
        }).get().join(',');

        var formContent =getChecks('form') ;
        formContent.group_id=$('.group-id').val();
        //发送提交请求
        var callable;
        if (method == 'post') {
            callable = $.post;
        } else {
            callable = $.get;
        }
        callable(action, formContent, function (a) {
            handleAjax(a);
            $('[type=submit]', form).removeClass('disabled');
        });

        //返回
        return false;
    });

    /**
     * 绑定全局操作
     * 权限操作赋予列表进行
     *
     */
    $(document).on('click', '.checkbox-select-all', function (e) {
        var mainChecked =$(this).parents('.cbr-replaced').hasClass('cbr-checked');
        console.log(mainChecked);
       var checks =$(this).parents('.panel-heading').next('.panel-body').find("div.cbr-replaced");
       checks.map(function(index,domElement){
           if(mainChecked){
               $(domElement).removeClass('cbr-checked');
           }else{
               $(domElement).addClass('cbr-checked');

           }

       });

    });
    function handleAjax(a) {
        //如果需要跳转的话，消息的末尾附上即将跳转字样
        if (a.url) {
            a.info += '，页面即将跳转～';
        }
        tips(a);
        //需要跳转的话就跳转
        var interval = 800;
        if (a.url == "refresh") {
            setTimeout(function () {
                window.location.href = location.href;
            }, interval);
        } else if (a.url) {
            setTimeout(function () {
                window.location.href = a.url;
            }, interval);
        }
    }

    /**
     * 绑定列表操作栏目按钮
     *
     */
    $(document).on('click','button.operate-click',function(e){
         var type = $(this).attr('operate-type');
         var url =$(this).attr('operate-url');
         var content={};
         console.log(type);
         content.id=$($(this)).attr('operate-id');
         var callback;
         switch (type){
             case "post":
                 callback=$.post;
                 if($(this).hasClass('btn-danger')){
                     swal({   title: "删除",
                         text: "确定要删除该条记录？",
                         type: "warning",
                         showCancelButton: true,
                         confirmButtonColor: "#e61616",
                         confirmButtonText: "删除",
                         cancelButtonText:'取消',
                         closeOnConfirm: true,
                         allowOutsideClick:true
                         },
                         function(){
                             (function(e){
                                 e(url,content,function(res){
                                     tips(res);
                                     if(res.url){
                                        setTimeout(function(){
                                            window.location.href=res.url;
                                        },800);
                                     }
                                 })
                             })(callback);
                         });
                 }else{
                     (function(e){
                         e(url,content,function(res){
                             tips(res);
                             if(res.url){
                                 setTimeout(function(){
                                     window.location.href=res.url;
                                 },800);
                             }
                         })
                     })(callback);
                 }
                 break;
             case "get":
                 callback=$.get;
                 (function(e){
                     e(url,content,function(res){
                         tips(res);
                     })
                 })(callback);
                 break;
             case "link":
                 window.location.href=url+"?id="+content.id;
                 break;
             case "modal":
                 swal({title: "置顶操作",
                       text: "请输入置顶排序参数（非负整数，小数自动取整）",
                       type: "input",
                       imageUrl: "/static/images/settop.png",
                       showCancelButton: true,
                       closeOnConfirm: false,
                       animation: "slide-from-top",
                       inputPlaceholder: "置顶",
                       cancelButtonText:'取消',
                       confirmButtonText: '确定',
                       confirmButtonColor: '#76d22d',
                       allowOutsideClick:true
                     }, function(inputValue){
                               if (inputValue === false) return false;
                               if (inputValue === "") {
                                   swal.showInputError("请输入置顶参数");
                                   return false
                               }
                     callback=$.post;
                     content.recommend=inputValue;
                     (function(e){
                         e(url,content,function(res){
                             tipsSweetAlert(res);
                         })
                     })(callback);
                 });
                 break;
             case 'postTextChange':
                  callback=$.post;
                  if($(this).attr('operate-button-type')=='publish'){
                      content.publish='publish';
                  }else{
                      content.publish='notpublish';
                  }
                 (function(e){
                     e(url,content,function(res){
                         tips(res);
                         if(res.url){
                             setTimeout(function(){
                                 window.location.href=res.url;
                             },800);
                         }
                     })
                 })(callback);


                 break;
             default  :
                 console.log(type);
                 break;
             }
    });

    $(document).on('click','.admin-list-button-link',function(e){
        $url = $(this).attr('button-url');
        window.location.href=$url;
    });
    $(document).on('click','.admin-list-button-post',function(e){
        var res = getChecks('tbody');
        var url =$(this).attr('button-url');
        if(res.strlength==0){
            tips({status:0,info:'未选中对象'});
        }else{
            if($(this).hasClass('btn-danger')){
                callback=$.post;
                swal({   title: "删除",
                        text: "确定要删除所选记录？",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#e61616",
                        confirmButtonText: "删除",
                        closeOnConfirm: true
                    },
                    function(){
                        (function(e){
                            e(url,{ids:res.checks},function(res){
                                tips(res);
                                if(res.url){
                                    setTimeout(function(){
                                        window.location.href=res.url;
                                    },800);
                                }
                            })
                        })(callback);
                    });
            }


        }
    });

    /**
     * select下拉框 进行选择时，将下拉选择的数值以及key 保存在cookie中 cookie有效期为一个小时
     * 保存在cooike中  后端读取 页面刷新 愚蠢的方式。。。不过也是最简单的
     */
    $(document).on('change','.select-operate',function(e) {
        var key = $(this).attr('select-key');
        var value=$(this).find("option:selected").val();
        $.cookie(key,value);
        window.location.reload();
    });
    /**
     * 请求信息返回 torast 弹框
     *
     */
    function tips(a){
        toastr.options = {
            "closeButton": true,
            "debug": false,
            "newestOnTop": false,
            "progressBar": true,
            "positionClass": "toast-top-right",
            "preventDuplicates": false,
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }
        //弹出提示消息
        if (a.status) {
            toastr.success(a.info);
        } else {
            $('form.ajax-form [type=submit]').removeClass('disabled');
            toastr.error(a.info);
        }
    }

    /**
     * 专门为sweewalert配套使用的tips
     */
    function tipsSweetAlert(a){
        if (a.status) {
            swal("成功", "操作成功","success");
            if(a.url){
                setTimeout(function () {
                    window.location.href = a.url;
                }, 800);
            }
        } else {
            swal("失败", "操作失败","error")
        }
    }

    /**
     * 列表页面获取所有checkbox的值
     *
     */
    function getChecks(dom){
      var objs =$(dom+"  .cbr-checked ");
      var  checks= objs.map(function(index,domElement){
           return $(domElement).find("div input[type='checkbox']").attr('value');
       }).get().join(',');
       return {checks:checks,strlength:objs.length};
    }


});